var util = require('../../utils/util.js');
var api = require('../../config/api.js');
var app = getApp()

Page({
  data: {
    id:null,
    hideAdd: 0,
    imageArray: [],
    picUrls: []
  },
  onLoad: function (options) {
    let cxauth = wx.getStorageSync("cxauth");
      if (cxauth) {
        this.setData({
          cxauth: cxauth
        });
      }
    if (options.id) {
      this.setData({ id: parseInt(options.id)});
    } else {
      wx.showToast({  title: '输入错误...即将跳转',  icon: 'loading', duration: 500});
      wx.navigateTo({ url: "/pages/index/index" });
    } 
  },
  // 选择图片
  chooseimage:function(){
    var that = this;
    //防止重复提交，先清空，把每次选择的图push进数组
    that.data.img_url = [];
    wx.chooseImage({
      count: 9, // 默认9 
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有 
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有 
      success: function (res) {
        console.log("选择图片");
        console.log(res);
        if (res.tempFilePaths.length > 0){
          //图如果满了9张，不显示加图
          if (res.tempFilePaths.length == 9){
            that.setData({
              hideAdd: 1
            })
          }
          //把每次选择的图push进数组
          let img_url = [];
          for (let i = 0; i < res.tempFilePaths.length; i++) {
            img_url.push(res.tempFilePaths[i]);
          }
          that.setData({imageArray: img_url})
        }
      }
    }) 
  },
  //发布按钮事件
  send:function(){
    //图片上传
    let that = this;
    let img_url = that.data.imageArray;
    let addtrue = 0;
    let addfalse = 0;
    //由于图片只能一张一张地上传，所以用循环
    for (let i = 0; i < img_url.length; i++) {
      wx.uploadFile({
        //路径填你上传图片方法的地址
        url: api.uploadImageUrl,
        filePath: img_url[i],
        name: 'file',
        success: function (res) {
          console.log("发布按钮事件");
        console.log(res);
          var _res = JSON.parse(res.data);
          if (_res.code == 200){
            //添加图片内容
              util.request(api.albumPhotoFabu, {
                cid: that.data.id,
                uid: wx.getStorageSync('userInfo').id,
                type: 10,
                name:_res.data.name,
                url: _res.data.url,
                ext: _res.data.ext,
                size: _res.data.size
              }, 'POST').then(function(res) {
                if(res.code == 200){
                  // 上传成功进行计数
                  addtrue = addtrue+1;
                } else {
                  // 上传失败进行计数
                  addfalse = addfalse+1;
                }
              })           
          }
          wx.showModal({
            title: "提交成功",
            showCancel: true,
          })
        },fail: function (res) {
          console.log('上传失败')
        }
      })
    }
    // wx.showModal({
    //   title: "提交成功"+addtrue+"张，失败"+addfalse+"张",
    //   showCancel: true,
    // })
  } 
})